from flask import Flask, request, jsonify, send_from_directory
from flask_cors import CORS
import os
import cv2
import numpy as np
import json

app = Flask(__name__)
CORS(app)
UPLOAD_FOLDER = 'uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

# 简化的神经网络识别函数
def recognize_video(video_path):
    print('recognize video')
    cap = cv2.VideoCapture(video_path)
    results = []
    frame_count = 0

    while cap.isOpened():
        frame_count += 1
        if frame_count % 10000 != 0:
            continue
        ret, frame = cap.read()
        if not ret:
            break

        # 模拟识别结果
        result = {
            'time': frame_count / cap.get(cv2.CAP_PROP_FPS),
            'result': '示例结果',
            'latitude': 51.505,  # 示例纬度
            'longitude': -0.09  # 示例经度
        }
        results.append(result)
        if(len(results) >= 10):
            break
    cap.release()
    print('recognize done', len(results))
    return results

@app.route('/upload', methods=['POST'])
def upload_video():
    print('request video')
    if 'video' not in request.files:
        return jsonify({'error': '未上传视频'}), 400

    video_file = request.files['video']
    video_path = os.path.join(app.config['UPLOAD_FOLDER'], video_file.filename)
    video_file.save(video_path)

    results = recognize_video(video_path)
    video_url = f'/uploads/{video_file.filename}'

    return jsonify({
        'videoUrl': video_url,
        'results': results
    })

@app.route('/uploads/<path:filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename)

if __name__ == '__main__':
    if not os.path.exists(UPLOAD_FOLDER):
        os.makedirs(UPLOAD_FOLDER)
    app.run(debug=True, port=5000, host='0.0.0.0')